<?php
namespace app\admin\controller;

use think\Controller;
use app\admin\model\Archive as Archives;
use app\admin\model\Arctype;
use app\admin\model\ArctypeMod;
use think\Db;

class Archive extends Common
{
    private $cModel;   //当前控制器关联模型
    
    public function _initialize()
    {
        parent::_initialize();
        $this->cModel = new Archives;   //别名：避免与控制名冲突
    }
    
    public function index()
    {
        $where = [];
        if (input('get.search')){
            $where['title|keywords|description'] = ['like', '%'.input('get.search').'%'];
        }
        if (input('get._sort')){
            $order = explode(',', input('get._sort'));
            $order = $order[0].' '.$order[1];
        }else{
            $order = 'id desc';
        }
        $dataList = $this->cModel->where($where)->order($order)->paginate('', false, page_param());
        foreach ($dataList as $k => $v){
            $dataList[$k]['holdid'] = Db('arctype')->where('id',$v['holdid'])->value('typename');
        }
        $this->assign('dataList', $dataList);
        return $this->fetch();
    }
    
    public function create($typeid)
    {
        if (request()->isPost()){
            Db::startTrans();
            try{
                $data = input('post.');
                $data['create_time'] = strtotime($data['create_time']);
                if (isset($data['flag']) || isset($data['litpic'])){
                    $data['flag'] = $this->_flag($data['flag'], $data['litpic']);
                }
                //
                $pid = Db('arctype')->where('id',$data['typeid'])->value('pid');
                $data['holdid'] = Db('arctype')->where('id',$pid)->value('id');
                $result = $this->cModel->validate(CONTROLLER_NAME.'.add')->allowField(true)->save($data);
                $data['aid'] = $this->cModel->getLastInsID();
                // 提交事务
                if ($result){
                    Db::commit();
                    return ajaxReturn(lang('action_success'), url('Arctype/index'));
                }else{
                    return ajaxReturn($this->cModel->getError());
                }
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return ajaxReturn($e->getMessage());
            }
        }else{
            $atModel = new Arctype();
            $arctypeList = $atModel->treeList();
            $this->assign('arctypeList', $arctypeList);
            
            $arcData = $atModel->where(['id' => $typeid])->find();   //栏目数据
            
            $data['typeid'] = $arcData['id'];
            $data['create_time'] = date('Y-m-d H:i:s', time());
            //$data['mid'] = $arcData['mid'];
            $this->assign('data', $data);
            
            return $this->fetch('edit');
        }
    }
    
    public function edit($id)
    {
        if (request()->isPost()){
            $data = input('post.');
            if (isset($data['create_time'])){
                $data['create_time'] = strtotime($data['create_time']);
            }
            if (isset($data['flag']) || isset($data['litpic'])){
                $data['flag'] = $this->_flag($data['flag'], $data['litpic']);
            }
            $pid = Db('arctype')->where('id',$data['typeid'])->value('pid');
            $data['holdid'] = Db('arctype')->where('id',$pid)->value('id');
            if (count($data) == 2){
                foreach ($data as $k =>$v){
                    $fv = $k!='id' ? $k : '';
                }
                $result = $this->cModel->validate(CONTROLLER_NAME.'.'.$fv)->allowField(true)->save($data, $data['id']);
            }else{
                $result = $this->cModel->validate(CONTROLLER_NAME.'.edit')->allowField(true)->save($data, $data['id']);
                $mod = $data['mod'];
                $addonData = db($mod)->field('id', true)->strict(false)->where( 'aid='.$data['id'] )->update($data);   //关联表数据
            }
            if ($result){
                return ajaxReturn(lang('action_success'), url('index'));
            }else{
                return ajaxReturn($this->cModel->getError());
            }
        }else{
            $atModel = new Arctype();
            $arctypeList = $atModel->treeList();
            $this->assign('arctypeList', $arctypeList);
            
            $data = $this->cModel->get($id);
            $addonMod = $data['mod'];
            $data['addondata'] = $data->$addonMod;   //拓展表数据
            unset($data[$data['mod']]);
            
            $atmModel = new ArctypeMod();
            $data['mid'] = $atmModel->where(['mod' => $addonMod])->value('id');
            
            $this->assign('mods', $addonMod);
            
            if (!empty($data['flag'])){
                $data['flag'] = explode(',', $data['flag']);
            }
            $this->assign('data', $data);
            return $this->fetch();
        }
    }
    
    public function delete()
    {
        if (request()->isPost()){
            $id = input('id');
            if (isset($id) && !empty($id)){
                $id_arr = explode(',', $id);
                if (!empty($id_arr)){
                    foreach ($id_arr as $val){
                        $addonMod = $this->cModel->where(['id' => $val])->value('mod');
                        $this->cModel->where('id='.$val)->delete();
                        db($addonMod)->where('aid='.$val)->delete();   //关联表数据
                    }
                    return ajaxReturn(lang('action_success'), url('index'));
                }else{
                    return ajaxReturn(lang('action_fail'));
                }
            }
        }
    }
    
    private function _flag($flag, $litpic)
    {
        if(empty($flag)){ $flag=array(); }
        if($litpic != ''){
            array_push($flag, "p");
        }else{
            $flag = unset_array("p", $flag);
        }
        $flag_arr = array_unique($flag);
        $result = implode(',', $flag_arr );
        return $result;
    }

     public function import(){
        $holdid = request()->param('holdid');
        $file = $this->request->file('imgFile');
        if($file){
            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads'.DS.'files');
            if($info){
                $path = ROOT_PATH . 'public' . DS . 'uploads'.DS.'files'.DS.$info->getSaveName();
            }else{
                // 上传失败获取错误信息
                return ajaxReturn($file->getError());
            }
        }

      ini_set('memory_limit','800M');
      //
      error_reporting(E_ALL);
      /** Include path **/
      set_include_path(get_include_path() . PATH_SEPARATOR . VENDOR_PATH.'/PHPExcel/Classes/');
        
      /** PHPExcel */
      vendor('PHPExcel.Classes.PHPExcel');

      /** PHPExcel_IOFactory */
      vendor('PHPExcel/Classes/PHPExcel/IOFactory');

      //vendor('PHPExcel/Classes/PHPExcel/Shape/Date.php');

      //$shared = new \PHPExcel_Shared_Date();

      $objPHPExcel = new \PHPExcel();
      //var_dump($info);ExcelToArray()
      //if ($info['xls']['ext']=='xls') {
      $objReader = \PHPExcel_IOFactory::createReader('Excel5');
      // }else{
      //     $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
      // }
      $objPHPExcel = $objReader->load($path,$encode='utf-8');
      $sheet = $objPHPExcel->getSheet(0);
      $highestRow = $sheet->getHighestRow(); // 取得总行数
      //$highestColumn = $sheet->getHighestColumn(); // 取得总列数
    $arr=array();

    for($i=2;$i<=$highestRow;$i++){
        $data=array();
        $data['title']=  $objPHPExcel->getActiveSheet()->getCell("A".$i)->getValue();
        $typename = $objPHPExcel->getActiveSheet()->getCell("B".$i)->getValue();
        $typeid = Db('arctype')->where('typename',$typename)->value('id');
        if (!$typeid) {
            $rs = Db('arctype')->insert(['typename'=>$typename,'pid'=>$holdid]);
            $data['typeid'] = Db('arctype')->getLastInsID();
        }else{
            $data['typeid'] = $typeid;
        }
        $data['holdid'] = $holdid;
        $data['description']=  $objPHPExcel->getActiveSheet()->getCell("C".$i)->getValue();
        $data['create_time'] = time();
        $data['update_time'] = time();
        $arr[] = $data;
    }
    $rs = $this->cModel->insertAll($arr);
    if ($rs) {
        return ajaxReturn(lang('action_success'), url('index'));
    }else{
        return ajaxReturn($this->cModel->getError());
    }

    }


     public function download(){
         ob_end_clean();
         ob_start();
         vendor('PHPExcel/Classes/PHPExcel');
        $cfg_columns = array(
            'id'=>array('name'=>lang('id')),
            'title'=>array('name'=>lang('title')),
            'holdid'=>array('name'=>lang('holdid')),
            'typeid'=>array('name'=>lang('typeid')),
            'description'=>array('name'=>lang('description')),
            //'dept_name'    => array('name'  => '部门','type'    => 'label','width' => 100),
        );
        $dataList = $this->cModel->all();
        
        $dataList = $this->cModel->where($where)->order($order)->paginate('', false, page_param());
        foreach ($dataList as $k => $v){
            $dataList[$k]['holdid'] = Db('arctype')->where('id',$v['holdid'])->value('typename');
            $dataList[$k]['typeid'] = $v->Arctype->typename;
        }

        $list = array();
        foreach ($dataList as $key => $value) {
            $list[] = $value->toArray();
        }

        $filename = 'hold.xls';
        header('Pragma:public');
        header('Content-Type:application/x-msexecl;name="'.$filename.'"');
        header('Content-Disposition:inline;filename="'.$filename.'"');

        $objPHPExcel = new \PHPExcel();

        $objPHPExcel->getActiveSheet(0)->mergeCells('B1:D1');
        $export_time = date('Y-m-d H:i:s');
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', '导出时间:');
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('B1', $export_time);

        $cols = 'A';
        foreach ($cfg_columns as $val){
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cols++.'2',$val['name']);
        }

        //第三行, 输出详细数据
        $rows = 3;
        foreach ($list as $fields){
            $cols = 'A';
            //按cfg_column的配置项导出
            foreach ($cfg_columns as $k => $val){
                if(empty( $fields[$k])){
                    $objPHPExcel->getActiveSheet()->setCellValue($cols++.$rows, 0);
                }else{
                    $objPHPExcel->getActiveSheet()->setCellValue($cols++.$rows, $fields[$k]);
                }

            } 

            $rows ++;
        }
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }
}